package com.gitee.limaozhi.socket.lesson03.example4;

import com.gitee.limaozhi.socket.lesson03.example3.Handler;
import com.gitee.limaozhi.socket.lesson03.example3.HandlerAdapter;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * HTTP编码器
 *
 * @author hzlimaozhi
 * @date 2019/08/07 11:36
 */
public class HttpEncoderHandler extends HandlerAdapter {

    private int prevReq = -1;
    private AtomicInteger req = new AtomicInteger(0);
    private boolean fireFinish = false;

    @Override
    public Handler handle(Object object) {
        HttpResponse response = (HttpResponse) object;
        String raw = response.raw();

        next().handle(raw.getBytes());
        req.incrementAndGet();
        fireFinish();
        return this;
    }

    @Override
    public Handler finish(int prevReq) {
        this.prevReq = prevReq;
        fireFinish();
        return this;
    }

    private synchronized void fireFinish() {
        if (!fireFinish) {
            if (prevReq == req.get()) {
                fireFinish = true;
//                context().print(context().getName() + "：Encoder：" + req.get());
                next().finish(req.get());
            }
        }
    }

}
